package cn.superchart.web.core.handler;

import cn.superchart.common.base.BaseJwtUser;
import cn.superchart.common.base.BaseUserDetails;
import cn.superchart.common.enums.ExceptionEnum;
import cn.superchart.common.exception.ScException;
import cn.superchart.common.utils.CacheContext;
import cn.superchart.common.utils.Checker;
import cn.superchart.common.utils.JwtUtils;
import cn.superchart.common.utils.ScUserContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
@Component
public class ScJwtAuthenticationTokenHandler extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        boolean isOptions = HttpMethod.OPTIONS.toString().equals(request.getMethod());
        log.info("请求地址:{} Method:{}",request.getRequestURI(),request.getMethod());
        if(isOptions || isWhiteList()){
            response.setStatus(HttpServletResponse.SC_OK);
            filterChain.doFilter(request, response);
            return;
        }
        //获取token
        String token = request.getHeader("Token");
        if (Checker.BeBlank(token)) {
            filterChain.doFilter(request,response);
            return;
        }
        BaseJwtUser baseJwtUser = JwtUtils.getUser(token);
        //解析token
        if (Checker.BeNull(baseJwtUser)){
            throw new ScException(ExceptionEnum.TOKEN_FORBIDDEN);
        }
        BaseUserDetails cacheUser = CacheContext.gutUserCache(baseJwtUser.getUserId());
        if (Checker.BeNull(cacheUser)){
             throw new ScException(ExceptionEnum.TOKEN_FORBIDDEN);
        }
        //存入SecurityContextHolder
//        BaseUserDetails baseUserDetails = new BaseUserDetails(baseJwtUser.getAccount(),baseJwtUser.getUserId());
//        baseUserDetails.setAuthorities(cacheUser.getAuthorities());
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(cacheUser,null, cacheUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }

    private boolean isWhiteList(){
        return ScUserContext.checkUrlIgnore();
    }
}
